package com.pxr.tutorial.xmltest;

import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class Main extends ListActivity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listplaceholder);

		ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
		final CopyFunctions cf = new CopyFunctions() ;


		String xml = XMLfunctions.getXML("http://citeyes.net/xmll.xml");
		Document doc = XMLfunctions.XMLfromString(xml);

		int numResults = XMLfunctions.numResults(doc);

		if((numResults <= 0)){
			Toast.makeText(Main.this, "pas resultats", Toast.LENGTH_LONG).show();  
			finish();
		}

		NodeList nodes = doc.getElementsByTagName("file");

		for (int i = 0; i < nodes.getLength(); i++) {							
			HashMap<String, String> map = new HashMap<String, String>();	

			Element e = (Element)nodes.item(i);
			map.put("file", "file: " + XMLfunctions.getValue(e, "file"));
			//map.put("name", "Naam:" + XMLfunctions.getValue(e, "name"));
			//map.put("Score", "Score: " + XMLfunctions.getValue(e, "score"));
			mylist.add(map);			
		}		

		ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main, 
				new String[] { "file", "status" }, 
				new int[] { R.id.item_title, R.id.item_subtitle });

		setListAdapter(adapter);

		final ListView lv = getListView();
		lv.setTextFilterEnabled(true);	
		lv.setOnItemClickListener(new OnItemClickListener() {
			@SuppressWarnings("unchecked")


			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

				HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);	   


				try {
					if(cf.copyFile(o.get("file"), "")){

						new Thread(new Runnable() {
							public void run() {
								String statusxml = XMLfunctions.getXML("http://citeyes.net/xmll.xml");
								

							}
						}).start();
						Toast.makeText(Main.this, "File '" + o.get("file") + "' was copied.", Toast.LENGTH_LONG).show(); 

					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}




			}
		});
	}
}